<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';

import { message, Modal } from 'ant-design-vue';

import ConsumptionHistoryModal from './components/ConsumptionHistoryModal.vue';
// 导入模态框组件
import CustomerFormModal from './components/CustomerFormModal.vue';
import DepositModal from './components/DepositModal.vue';
import MembershipCardModal from './components/MembershipCardModal.vue';
import PetFormModal from './components/PetFormModal.vue';
import WechatQRModal from './components/WechatQRModal.vue';

// 接口定义
interface Pet {
  id: string;
  name: string;
  type: 'bird' | 'cat' | 'dog' | 'other' | 'rabbit';
  gender: 'female' | 'male' | 'unknown';
  breed: string;
  color: string;
  age: number;
  weight: number;
  neutered: boolean;
  dewormed: boolean;
  vaccinated: boolean;
  deceased: boolean;
  notes: string;
}

interface MembershipCard {
  id: string;
  type: 'membership' | 'times';
  cardNumber: string;
  cardType: string;
  balance: number;
  giftAmount: number;
  issueDate: string;
  password?: string;
}

interface Customer {
  id: string;
  name: string;
  phone: string;
  email: string;
  gender: 'female' | 'male';
  age: number;
  address: string;
  source: string;
  deposit: number;
  points: number;
  registrationDate: string;
  pets: Pet[];
  membershipCards: MembershipCard[];
}

// 响应式数据
const customers = ref<Customer[]>([]);
const selectedCustomer = ref<Customer | null>(null);
const selectedPet = ref<null | Pet>(null);
const searchQuery = ref('');
const editingCustomer = ref<Customer | null>(null);
const editingPet = ref<null | Pet>(null);

// 模态框状态
const modals = ref({
  customerForm: false,
  petForm: false,
  membershipCard: false,
  deposit: false,
  consumptionHistory: false,
  wechatQR: false,
});

// 计算属性
const filteredCustomers = computed(() => {
  if (!searchQuery.value) return customers.value;

  return customers.value.filter(
    (customer) =>
      customer.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      customer.phone.includes(searchQuery.value),
  );
});

const totalPets = computed(() => {
  return customers.value.reduce(
    (total, customer) => total + customer.pets.length,
    0,
  );
});

const totalCards = computed(() => {
  return customers.value.reduce(
    (total, customer) => total + customer.membershipCards.length,
    0,
  );
});

const totalDeposit = computed(() => {
  return customers.value.reduce(
    (total, customer) => total + customer.deposit,
    0,
  );
});

// 方法
const searchCustomers = () => {
  // 搜索逻辑已在计算属性中实现
};

const selectCustomer = (customer: Customer) => {
  selectedCustomer.value = customer;
  selectedPet.value = null;
};

const selectPet = (pet: Pet) => {
  selectedPet.value = pet;
};

// 模态框显示方法
const showAddCustomerModal = () => {
  editingCustomer.value = null;
  modals.value.customerForm = true;
};

const showEditCustomerModal = () => {
  editingCustomer.value = selectedCustomer.value;
  modals.value.customerForm = true;
};

const showAddPetModal = () => {
  editingPet.value = null;
  modals.value.petForm = true;
};

const showAddCardModal = () => {
  modals.value.membershipCard = true;
};

const showDepositModal = () => {
  modals.value.deposit = true;
};

const showConsumptionHistory = () => {
  modals.value.consumptionHistory = true;
};

const showWechatQRModal = () => {
  modals.value.wechatQR = true;
};

const showQuickAppointment = () => {
  if (!selectedPet.value) {
    message.warning('请先选择一个宠物');
    return;
  }
  message.info(`为宠物 ${selectedPet.value.name} 快速预约`);
};

const showQuickRegistration = () => {
  if (!selectedPet.value) {
    message.warning('请先选择一个宠物');
    return;
  }
  message.info(`为宠物 ${selectedPet.value.name} 快速挂号`);
};

// 宠物相关操作
const editPet = (pet: Pet) => {
  editingPet.value = pet;
  modals.value.petForm = true;
};

const deletePet = (pet: Pet) => {
  Modal.confirm({
    title: '删除宠物',
    content: `确定要删除宠物 ${pet.name} 吗？此操作不可恢复。`,
    okType: 'danger',
    onOk: () => {
      if (selectedCustomer.value) {
        const index = selectedCustomer.value.pets.findIndex(
          (p) => p.id === pet.id,
        );
        if (index !== -1) {
          selectedCustomer.value.pets.splice(index, 1);
          message.success(`宠物 ${pet.name} 已删除`);
        }
      }
    },
  });
};

// 会员卡相关操作
const viewCardUsage = (card: MembershipCard) => {
  message.info(`查看会员卡 ${card.cardNumber} 的使用记录`);
};

const refundCard = (card: MembershipCard) => {
  Modal.confirm({
    title: '退卡确认',
    content: `确定要退还会员卡 ${card.cardNumber} 吗？余额将退还给顾客。`,
    onOk: () => {
      message.success(`会员卡 ${card.cardNumber} 已退还`);
    },
  });
};

const rechargeCard = (card: MembershipCard) => {
  message.info(`为会员卡 ${card.cardNumber} 充值`);
};

// 删除顾客
const deleteCustomer = () => {
  if (!selectedCustomer.value) return;

  Modal.confirm({
    title: '删除顾客',
    content: `确定要删除顾客 ${selectedCustomer.value.name} 吗？此操作将删除所有相关数据。`,
    okType: 'danger',
    onOk: () => {
      const index = customers.value.findIndex(
        (c) => c.id === selectedCustomer.value?.id,
      );
      if (index !== -1) {
        customers.value.splice(index, 1);
        selectedCustomer.value = null;
        message.success('顾客已删除');
      }
    },
  });
};

// 模态框回调
const handleCustomerSuccess = () => {
  message.success('顾客信息保存成功');
  modals.value.customerForm = false;
  editingCustomer.value = null;
};

const handlePetSuccess = () => {
  message.success('宠物信息保存成功');
  modals.value.petForm = false;
  editingPet.value = null;
};

const handleCardSuccess = () => {
  message.success('会员卡创建成功');
  modals.value.membershipCard = false;
};

const handleDepositSuccess = () => {
  message.success('押金操作成功');
  modals.value.deposit = false;
};

// 初始化数据
onMounted(() => {
  // 模拟数据
  customers.value = [
    {
      id: 'C001',
      name: '赵女士',
      phone: '18300138001',
      email: 'zhao@example.com',
      gender: 'female',
      age: 30,
      address: '伯爵路123号',
      source: '朋友推荐',
      deposit: 50,
      points: 0,
      registrationDate: '2019-08-06',
      pets: [
        {
          id: 'P000002',
          name: '球球',
          type: 'dog',
          gender: 'unknown',
          breed: '金毛',
          color: '黑色',
          age: 3,
          weight: 25,
          neutered: false,
          dewormed: false,
          vaccinated: false,
          deceased: false,
          notes: '定期体检',
        },
        {
          id: 'P000004',
          name: '蛋蛋',
          type: 'cat',
          gender: 'unknown',
          breed: '英短',
          color: '灰色',
          age: 2,
          weight: 4,
          neutered: false,
          dewormed: false,
          vaccinated: false,
          deceased: false,
          notes: '已绝育',
        },
      ],
      membershipCards: [
        {
          id: 'MC001',
          type: 'membership',
          cardNumber: '002',
          cardType: '金卡',
          balance: 1986,
          giftAmount: 100,
          issueDate: '2019-06-08',
        },
      ],
    },
    {
      id: 'C002',
      name: '王先生',
      phone: '18243535',
      email: 'wang@example.com',
      gender: 'male',
      age: 35,
      address: '市中心456号',
      source: '网络搜索',
      deposit: 100,
      points: 50,
      registrationDate: '2019-07-15',
      pets: [
        {
          id: 'P000003',
          name: '旺财',
          type: 'dog',
          gender: 'male',
          breed: '拉布拉多',
          color: '黄色',
          age: 1,
          weight: 20,
          neutered: true,
          dewormed: true,
          vaccinated: true,
          deceased: false,
          notes: '幼犬',
        },
      ],
      membershipCards: [],
    },
  ];

  // 默认选择第一个顾客
  if (customers.value.length > 0) {
    selectedCustomer.value = customers.value[0];
  }
});
</script>

<template>
  <div class="customer-info-page">
    <div class="page-container">
      <!-- 左侧：顾客列表 -->
      <div class="customer-list-panel">
        <div class="panel-header">
          <h3>👥 顾客列表</h3>
          <a-button type="primary" @click="showAddCustomerModal">
            ➕ 新增顾客/宠物
          </a-button>
        </div>

        <div class="search-section">
          <a-input
            v-model:value="searchQuery"
            placeholder="顾客/手机号"
            @keyup.enter="searchCustomers"
            @change="searchCustomers"
          >
            <template #suffix>
              <a-button type="text" @click="searchCustomers">🔍</a-button>
            </template>
          </a-input>
        </div>

        <div class="customer-list">
          <div
            v-for="customer in filteredCustomers"
            :key="customer.id"
            class="customer-item"
            :class="{ active: selectedCustomer?.id === customer.id }"
            @click="selectCustomer(customer)"
          >
            <div class="customer-avatar">
              <a-avatar :size="40">
                {{ customer.name.charAt(0) }}
              </a-avatar>
            </div>
            <div class="customer-info">
              <div class="customer-name">{{ customer.name }}</div>
              <div class="customer-phone">{{ customer.phone }}</div>
              <div class="customer-pets">
                <span class="pet-count">{{ customer.pets.length }}只宠物</span>
                <span class="card-count"
                  >{{ customer.membershipCards.length }}张卡</span
                >
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 中间：顾客详细信息 -->
      <div class="customer-detail-panel" v-if="selectedCustomer">
        <div class="panel-header">
          <div class="customer-title">
            <h2>{{ selectedCustomer.name }}</h2>
            <a-button type="link" @click="showEditCustomerModal">
              修改顾客信息
            </a-button>
          </div>
          <div class="registration-date">
            登记日期: {{ selectedCustomer.registrationDate }}
            <a-button type="text" @click="showWechatQRModal">
              📱 微信关注
            </a-button>
          </div>
        </div>

        <!-- 顾客基本信息 -->
        <a-card title="👤 顾客信息" class="info-card">
          <a-row :gutter="16">
            <a-col :span="8">
              <div class="info-item">
                <label>姓名:</label>
                <span>{{ selectedCustomer.name }}</span>
              </div>
            </a-col>
            <a-col :span="8">
              <div class="info-item">
                <label>手机:</label>
                <span>{{ selectedCustomer.phone }}</span>
              </div>
            </a-col>
            <a-col :span="8">
              <div class="info-item">
                <label>邮箱:</label>
                <span>{{ selectedCustomer.email || '未填写' }}</span>
              </div>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="8">
              <div class="info-item">
                <label>性别:</label>
                <span>{{
                  selectedCustomer.gender === 'female' ? '女' : '男'
                }}</span>
              </div>
            </a-col>
            <a-col :span="8">
              <div class="info-item">
                <label>年龄:</label>
                <span>{{ selectedCustomer.age }}岁</span>
              </div>
            </a-col>
            <a-col :span="8">
              <div class="info-item">
                <label>住址:</label>
                <span>{{ selectedCustomer.address }}</span>
              </div>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="8">
              <div class="info-item">
                <label>了解途径:</label>
                <span>{{ selectedCustomer.source || '未填写' }}</span>
              </div>
            </a-col>
            <a-col :span="8">
              <div class="info-item">
                <label>押金:</label>
                <span class="deposit-amount"
                  >¥{{ selectedCustomer.deposit.toFixed(2) }}</span
                >
                <a-button type="link" size="small" @click="showDepositModal">
                  押金管理
                </a-button>
              </div>
            </a-col>
            <a-col :span="8">
              <div class="info-item">
                <label>积分:</label>
                <span>{{ selectedCustomer.points.toFixed(2) }}</span>
              </div>
            </a-col>
          </a-row>
        </a-card>

        <!-- 会员卡/次卡 -->
        <a-card title="💳 会员卡/次卡" class="info-card">
          <div class="card-list">
            <div
              v-for="card in selectedCustomer.membershipCards"
              :key="card.id"
              class="membership-card"
            >
              <div class="card-header">
                <div class="card-type">{{ card.type }}</div>
                <div class="card-number">卡号: {{ card.cardNumber }}</div>
              </div>
              <div class="card-balance">
                <div class="balance-amount">¥{{ card.balance.toFixed(2) }}</div>
                <div class="gift-amount" v-if="card.giftAmount > 0">
                  赠额: ¥{{ card.giftAmount.toFixed(2) }}
                </div>
              </div>
              <div class="card-actions">
                <a-button type="link" size="small" @click="viewCardUsage(card)">
                  使用记录
                </a-button>
                <a-button type="link" size="small" @click="refundCard(card)">
                  退卡
                </a-button>
                <a-button type="link" size="small" @click="rechargeCard(card)">
                  充值
                </a-button>
              </div>
            </div>
            <div class="add-card-button">
              <a-button type="dashed" @click="showAddCardModal">
                ➕ 添加会员卡/次卡
              </a-button>
            </div>
          </div>
        </a-card>

        <!-- 宠物列表 -->
        <a-card title="🐾 宠物列表" class="info-card">
          <div class="pet-list">
            <div
              v-for="pet in selectedCustomer.pets"
              :key="pet.id"
              class="pet-item"
              :class="{ selected: selectedPet?.id === pet.id }"
              @click="selectPet(pet)"
            >
              <div class="pet-avatar">
                <a-avatar :size="50">
                  {{
                    pet.type === 'dog' ? '🐕' : pet.type === 'cat' ? '🐱' : '🐾'
                  }}
                </a-avatar>
              </div>
              <div class="pet-info">
                <div class="pet-name">{{ pet.name }}</div>
                <div class="pet-details">
                  <span>编号: {{ pet.id }}</span>
                  <span>性别: {{ pet.gender === 'male' ? '公' : '母' }}</span>
                  <span>品种: {{ pet.breed || '未知' }}</span>
                </div>
                <div class="pet-status">
                  <a-tag :color="pet.neutered ? 'green' : 'orange'">
                    {{ pet.neutered ? '已去势' : '去势未知' }}
                  </a-tag>
                  <a-tag :color="pet.dewormed ? 'green' : 'orange'">
                    {{ pet.dewormed ? '已驱虫' : '驱虫未知' }}
                  </a-tag>
                  <a-tag :color="pet.vaccinated ? 'green' : 'orange'">
                    {{ pet.vaccinated ? '已免疫' : '免疫未知' }}
                  </a-tag>
                </div>
              </div>
              <div class="pet-actions">
                <a-button type="link" size="small" @click="editPet(pet)">
                  编辑
                </a-button>
                <a-button
                  type="link"
                  size="small"
                  danger
                  @click="deletePet(pet)"
                >
                  删除
                </a-button>
              </div>
            </div>
            <div class="add-pet-button">
              <a-button type="dashed" @click="showAddPetModal">
                ➕ 添加宠物
              </a-button>
            </div>
          </div>
        </a-card>

        <!-- 底部操作按钮 -->
        <div class="bottom-actions">
          <a-space>
            <a-button @click="showConsumptionHistory">
              📊 个人消费记录查询
            </a-button>
            <a-button danger @click="deleteCustomer"> 🗑️ 删除顾客 </a-button>
            <a-button type="primary" @click="showQuickAppointment">
              📅 快速预约
            </a-button>
            <a-button type="primary" @click="showQuickRegistration">
              🏥 快速挂号
            </a-button>
          </a-space>
        </div>
      </div>

      <!-- 右侧：快速操作面板 -->
      <div class="quick-actions-panel">
        <div class="panel-header">
          <h3>⚡ 快速操作</h3>
        </div>

        <div class="quick-actions">
          <a-button type="primary" block @click="showAddCustomerModal">
            👤 新增顾客
          </a-button>
          <a-button type="primary" block @click="showAddPetModal">
            🐾 新增宠物
          </a-button>
          <a-button type="primary" block @click="showAddCardModal">
            💳 新增会员卡
          </a-button>
          <a-button type="primary" block @click="showDepositModal">
            💰 押金管理
          </a-button>
          <a-button type="primary" block @click="showConsumptionHistory">
            📊 消费记录
          </a-button>
          <a-button type="primary" block @click="showWechatQRModal">
            📱 微信关注
          </a-button>
        </div>

        <div class="statistics">
          <h4>📈 统计信息</h4>
          <div class="stat-item">
            <span>总顾客数:</span>
            <span class="stat-value">{{ customers.length }}</span>
          </div>
          <div class="stat-item">
            <span>总宠物数:</span>
            <span class="stat-value">{{ totalPets }}</span>
          </div>
          <div class="stat-item">
            <span>总会员卡:</span>
            <span class="stat-value">{{ totalCards }}</span>
          </div>
          <div class="stat-item">
            <span>总押金:</span>
            <span class="stat-value">¥{{ totalDeposit.toFixed(2) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 模态框组件 -->
    <CustomerFormModal
      v-model:visible="modals.customerForm"
      :customer="editingCustomer"
      @success="handleCustomerSuccess"
    />
    <PetFormModal
      v-model:visible="modals.petForm"
      :pet="editingPet"
      :customer="selectedCustomer"
      @success="handlePetSuccess"
    />
    <MembershipCardModal
      v-model:visible="modals.membershipCard"
      :customer="selectedCustomer"
      @success="handleCardSuccess"
    />
    <DepositModal
      v-model:visible="modals.deposit"
      :customer="selectedCustomer"
      @success="handleDepositSuccess"
    />
    <ConsumptionHistoryModal
      v-model:visible="modals.consumptionHistory"
      :customer="selectedCustomer"
    />
    <WechatQRModal
      v-model:visible="modals.wechatQR"
      :customer="selectedCustomer"
    />
  </div>
</template>

<style scoped>
.customer-info-page {
  height: 100vh;
  background: #f5f5f5;
}

.page-container {
  display: flex;
  gap: 16px;
  height: 100%;
  padding: 16px;
}

.customer-list-panel {
  display: flex;
  flex-direction: column;
  width: 300px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.customer-detail-panel {
  display: flex;
  flex: 1;
  flex-direction: column;
  overflow-y: auto;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.quick-actions-panel {
  display: flex;
  flex-direction: column;
  width: 250px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.customer-title {
  display: flex;
  gap: 12px;
  align-items: center;
}

.customer-title h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.registration-date {
  font-size: 14px;
  color: #666;
}

.search-section {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.customer-list {
  flex: 1;
  padding: 8px;
  overflow-y: auto;
}

.customer-item {
  display: flex;
  gap: 12px;
  align-items: center;
  padding: 12px;
  margin-bottom: 8px;
  cursor: pointer;
  border-radius: 6px;
  transition: all 0.3s;
}

.customer-item:hover {
  background: #f5f5f5;
}

.customer-item.active {
  background: #e6f7ff;
  border: 1px solid #91d5ff;
}

.customer-info {
  flex: 1;
}

.customer-name {
  margin-bottom: 4px;
  font-weight: 600;
}

.customer-phone {
  margin-bottom: 4px;
  font-size: 12px;
  color: #666;
}

.customer-pets {
  font-size: 11px;
  color: #999;
}

.pet-count,
.card-count {
  margin-right: 8px;
}

.info-card {
  margin: 16px;
  border-radius: 8px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.info-item label {
  width: 80px;
  margin-right: 8px;
  font-weight: 600;
  color: #666;
}

.deposit-amount {
  margin-right: 8px;
  font-weight: 600;
  color: #1890ff;
}

.card-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.membership-card {
  padding: 16px;
  background: #fafafa;
  border: 1px solid #d9d9d9;
  border-radius: 8px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.card-type {
  font-weight: 600;
  color: #1890ff;
}

.card-number {
  font-size: 12px;
  color: #666;
}

.card-balance {
  margin-bottom: 8px;
}

.balance-amount {
  font-size: 20px;
  font-weight: 700;
  color: #52c41a;
}

.gift-amount {
  font-size: 12px;
  color: #faad14;
}

.card-actions {
  display: flex;
  gap: 8px;
}

.pet-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.pet-item {
  display: flex;
  gap: 12px;
  align-items: center;
  padding: 12px;
  cursor: pointer;
  border: 1px solid #d9d9d9;
  border-radius: 8px;
  transition: all 0.3s;
}

.pet-item:hover {
  border-color: #1890ff;
}

.pet-item.selected {
  background: #e6f7ff;
  border-color: #1890ff;
}

.pet-info {
  flex: 1;
}

.pet-name {
  margin-bottom: 4px;
  font-weight: 600;
}

.pet-details {
  margin-bottom: 4px;
  font-size: 12px;
  color: #666;
}

.pet-details span {
  margin-right: 12px;
}

.pet-status {
  display: flex;
  gap: 4px;
}

.pet-actions {
  display: flex;
  gap: 4px;
}

.add-card-button,
.add-pet-button {
  padding: 16px;
  text-align: center;
}

.bottom-actions {
  padding: 16px;
  margin-top: auto;
  border-top: 1px solid #f0f0f0;
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 16px;
}

.statistics {
  padding: 16px;
  margin-top: auto;
  border-top: 1px solid #f0f0f0;
}

.statistics h4 {
  margin: 0 0 12px;
  font-size: 14px;
  font-weight: 600;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 12px;
}

.stat-value {
  font-weight: 600;
  color: #1890ff;
}

:deep(.ant-card-head) {
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.ant-card-body) {
  padding: 16px;
}
</style>
